package com.example.api;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/api/echo")
public class EchoServlet extends HttpServlet {

    // 处理 POST 请求
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        // 设置跨域
        resp.setHeader("Access-Control-Allow-Origin", "*"); // 或改成 http://127.0.0.1:8848
        resp.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS");
        resp.setHeader("Access-Control-Allow-Headers", "Content-Type");
        String id= req.getParameter("id");
        // 设置返回 JSON
        System.out.println(id);
        resp.setContentType("application/json;charset=UTF-8");

        String name = req.getParameter("name");
        if (name == null) {
            name = "未知用户";
        }

        resp.getWriter().write("{\"msg\":\"你好, " + name + "\"}");
    }

    // 处理预检请求 (OPTIONS)
    @Override
    protected void doOptions(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        resp.setHeader("Access-Control-Allow-Origin", "*");
        resp.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS");
        resp.setHeader("Access-Control-Allow-Headers", "Content-Type");
    }
}
